#include "xmlloader.h"

int
LoadXMLnode( StatList& list, rapidxml::xml_node<char> * node, std::string sname )
{
	if( !node )
		return -3;
	sname += ( sname.length() && node->name_size() ? "." : "" ) + std::string( node->name() );
	if( !node->first_attribute() && !node->last_attribute() )
	{
		list[ sname ] = std::string( node->value() );
	}
	else
	if( node->first_attribute() && node->first_attribute() != node->last_attribute() )
	{
		std::cout << "ERR: Multi-Attributed Node!!! Cannot Parse." << std::endl;
		return -1;
	}
	else
	if( node->first_attribute() && node->first_attribute() == node->last_attribute() )
	{
		std::string attname = std::string( node->first_attribute()->name() );
		std::string attvalue = std::string( node->first_attribute()->value() );
		if( !attname.compare( "int" ) )
		{
			int val = 0;
			int ssr = sscanf( attvalue.c_str(), "%d", &val );
			if( ssr != 1 )
			{
				std::cout << "ERR: 'int' Attribute failed parsing!!! Cannot Parse." << std::endl;
				return -2;
			}
			list[ sname ] = val;
		}
		else
		if(
			StringParser::startsWith( attname, "dint" ) ||
			StringParser::startsWith( attname, "roll" ) ||
			StringParser::startsWith( attname, "droll" ) ||
			StringParser::startsWith( attname, "stat" ) ||
			StringParser::startsWith( attname, "dstat" ) ||
			StringParser::startsWith( attname, "name" ) ||
			StringParser::startsWith( attname, "dname" ) ||
			StringParser::startsWith( attname, "type" ) ||
			StringParser::startsWith( attname, "modify" )
		)
		{
			list[ sname ] = attvalue;
			list[ sname ] |= attname;
		}
		else
		{
			if( node->value_size() )
			{
				list[ sname ] = std::string( node->value() );
				list[ sname ] |= "unknown";
			}
		}
	}
	else
	{
		std::cout << "ERR: Unknown Attribute set Cannot Parse." << std::endl;
		return -3;
	}

	rapidxml::xml_node<char> * childnode = node->first_node();
	if( childnode )
	{
		do
		{
			int recret = LoadXMLnode( list, childnode, sname );
			if( recret )
			{
				return recret;
			}
			if( childnode->next_sibling() )
				childnode = childnode->next_sibling();
		}
		while( childnode != node->last_node() );
	}

	return 0;
}



int
loadXMLintoStatList( StatList& list, rapidxml::xml_document<char>& doc )
{
	return LoadXMLnode( list, &doc, "" );
//	return 0;
}